#find_primer.pl
#author: Jeremy Cothran (jeremy.cothran@gmail.com)
#date: March 28, 2008

use strict;

my ($primer_file,$fasta_file,$direction) = @ARGV;

if (@ARGV < 2) { print "usage like : perl find_primer.pl primers.txt 1.TCA.454Reads.fna forward \n"; exit 0; }

my %sequences;

open (FILE_PRIMER,"primers.txt");
open (FILE_SUMMARY,">summary.txt");

print FILE_SUMMARY "#fasta file read:$fasta_file direction:$direction \n\n";
my $found_header = "#fasta file read:$fasta_file direction:$direction \n\n";

my $line;
while ($line = <FILE_PRIMER>) {

if ($line =~ /^#/ || $line =~ /^\s/ || length($line) < 5) { next; }

#print "$line".length($line)."\n";

my $found_file = '';
my $found_flag = 0;

my $primer_count = 0;

my ($primer, $seq) = split (/\s+/, $line);

my $adapter = substr($seq,0,19);
my $key = substr($seq,19,4);
my $main_seq = substr($seq,23);
chomp($main_seq);

print FILE_SUMMARY "$primer:$adapter:$key:$main_seq\n";

$found_file = $found_header;
$found_file .= "#$primer:$adapter:$key:$main_seq\n";

my $search_seq;

$search_seq = $key.$main_seq;

if ($direction eq 'reverse') {

#reverse
$search_seq = reverse $key.$main_seq;

#complement
$search_seq =~ tr/ACGT/TGCA/;

}

print FILE_SUMMARY "#search sequence: $search_seq\n";
$found_file .= "#search sequence: $search_seq\n";


###############################################

my $fasta_count = 0;
open (FILE_FASTA,"$fasta_file");

my $built_seq = '';

while (my $fasta_line = <FILE_FASTA>) {

if ($fasta_line =~ /^>/) {
	my $search_found = search_seq($primer, $main_seq, $search_seq, $built_seq);

	$primer_count += $search_found;

	my $seq_interest = substr($built_seq,length($search_seq));

	if ($search_found) {
		$sequences{$seq_interest}++;
		$found_file .= $fasta_line.$seq_interest."\n";
		$found_flag = 1;
	} 

	$built_seq = '';
	$fasta_count++;
	next;
}

else {
	chomp($fasta_line);
	$built_seq .= $fasta_line;
}

} #while fasta file

close (FILE_FASTA);

###########################

print FILE_SUMMARY "#final primer count: $primer_count / $fasta_count\n\n";

if ($found_flag) {

open(FILE_FOUND,">found/found_$primer.txt");
print FILE_FOUND $found_file;
close(FILE_FOUND);

}

} #while primer file

close(FILE_PRIMER);

my @unique = keys %sequences;

my $count = @unique;

print FILE_SUMMARY "sequence count = $count\n";

exit 0;

###############################################

sub search_seq {

my ($primer, $main_seq, $search_seq, $fasta_seq) = @_;

if ($fasta_seq =~ $search_seq) {

	#print "yes!\n";
	
	#print "$primer:$main_seq\n$search_seq\n:$fasta_seq:\n";
	
	return 1;
}

return 0;

}